package middleware

import (
	"context"
	"time"

	"catering_sys_api/cmd/api/dao"
	"catering_sys_api/core/errno"

	"github.com/cloudwego/hertz/pkg/app"
)

func AuthToken() app.HandlerFunc {
	return func(ctx context.Context, c *app.RequestContext) {
		var (
			err            error
			userDao        *dao.BusinessUserDao
			businessUserVo dao.BusinessUserVo
		)
		var tokenStruct struct {
			Token string `json:"token"`
		}
		_ = c.Bind(&tokenStruct)
		if len(tokenStruct.Token) > 0 {
			//解析token
			userDao = dao.NewBusinessUserDao(ctx)
			businessUserVo, err = userDao.GetBusinessUserVoByToken(tokenStruct.Token)

			if err == nil {
				c.Set("user_id", businessUserVo.UserId)
				c.Set("real_name", businessUserVo.RealName)
				c.Set("phone", businessUserVo.Phone)
				c.Set("business_id", businessUserVo.BusinessID)
				c.Set("business_name", businessUserVo.BusinessName)
				c.Set("start_time", businessUserVo.StartTime)
				c.Set("end_time", businessUserVo.EndTime)
			}
		}
	}
}

func AuthLogin() app.HandlerFunc {
	return func(ctx context.Context, c *app.RequestContext) {
		var (
			businessUserVo dao.BusinessUserVo
			userDao        *dao.BusinessUserDao
		)
		userDao = dao.NewBusinessUserDao(ctx)
		businessUserVo, _ = userDao.GetBusinessUserVoFromC(c)

		if businessUserVo.UserId == 0 {
			//重新登录 返回登录的错误吗
			errno.Fail(errno.USER_NO_LOGIN, "", "用户未登录", ctx, c)
			c.Abort()
			return
		}
	}
}

func CheckBusinessPower() app.HandlerFunc {
	return func(ctx context.Context, c *app.RequestContext) {
		var (
			businessUserVo dao.BusinessUserVo
			userDao        *dao.BusinessUserDao
			currentTime    int64
		)
		userDao = dao.NewBusinessUserDao(ctx)
		businessUserVo, _ = userDao.GetBusinessUserVoFromC(c)

		if businessUserVo.UserId > 0 {
			currentTime = time.Now().Unix()
			if currentTime < businessUserVo.StartTime || currentTime > businessUserVo.EndTime {
				errno.Fail(errno.FAIL_ERR, "", "该商户授权已过期，请及时续费", ctx, c)
				c.Abort()
				return
			}
			//重新登录 返回登录的错误吗

		}
	}
}
